import sys

from threading import Thread, Lock
from Queue import Queue

from Connection303 import Connection303
	
class ConnHopper():

	def __init__( self, url, ConnGenerator, ConnValidator ):
		(self._targetConn, self._Conns) = ConnGenerator( url )
		self._Validator = ConnValidator
		self._Results = []
		self._Queue = Queue( len(self._Conns) )
		self._ConnQLock = Lock()
		
	def _ConnBlast( self ):
		while True:
			self._ConnQLock.acquire()
			c=self._Queue.get()
			self._ConnQLock.release()
			c.connect()
			self._Queue.task_done()
			
	def getConns( self ):
		return self._Conns

	def results( self ):
		return self._Results

	def run( self ):
		for i in xrange(100):
			t=Thread(target=self._ConnBlast)
			t.daemon=True
			t.start()
		try:
			for newUrl in [self._targetConn]+self._Conns:
				self._Queue.put( newUrl )
			self._Queue.join()
		except KeyboardInterrupt:
			sys.exit(1)

		self._Results = [ (hit, self._Validator(self._targetConn,hit)) for hit in self._Conns ]
		#self._Results = [ tuple in self._Results if tuple[1] ]

